const fs = require('fs')
const path = require('path')
const {exec, execFile, execSync} = require('child_process')

//获取文件路径指定层级下的项目文件夹
export const loadDir = (val, level = 2, filter = []) => {
  level = level - 1
  const files = fs.readdirSync(val).filter((item) => {
    let fileType = getFileType(item)
    let fileTypeFilter = fileType && filter.indexOf(fileType) !== -1
    return !item.startsWith('.') && filter.indexOf(item) == -1 && !fileTypeFilter
  })
  if (level === 0) return files
  let dirObj = {}
  for (let i = 0; i < files.length; i++) {
    const fileItem = files[i]
    const fileItemDir = fs.lstatSync(`${val}/${fileItem}`)
    if (fileItemDir.isDirectory() && filter.indexOf(fileItem) === -1) {
      dirObj[fileItem] = loadDir(`${val}/${fileItem}`, level, filter)
    }
  }
  return dirObj
}

//获取当前时间
export const getCurrentTime = (emptyStr = false) => {
  let time = new Date()
  let year = time.getFullYear()

  let mm = time.getMonth() + 1
  mm = mm < 10 ? '0' + mm : mm
  let dd = time.getDate()
  dd = dd < 10 ? '0' + dd : dd
  let hh = time.getHours()
  let mf = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
  let ss = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
  let timeStr = `${year}-${mm}-${dd} ${hh}:${mf}:${ss}`
  if (emptyStr) timeStr = timeStr.replace(/./g, '=')
  return timeStr
}

//执行command命令
export const execCommand = (command) => {
  return new Promise((resolve, reject) => {
    if (command.indexOf('cd ') !== -1) {
      let dirPath = command.replace('cd ', '') //D:\WorkPlace\Git_Project
      try {
        process.chdir(dirPath)
        resolve({stdout: `进入目录【${process.cwd()}】成功！`})
      } catch (e) {
        console.log('cd command======error', e)
        reject(e)
      }
    } else if (command.indexOf('upload.sh ') !== -1) {
      let [p1, p2, p3] = command.split(' ').filter((item) => item)
      console.log('upload.sh ====', p1, p2, p3)
      execFile(path.resolve(__dirname, 'upload.sh'), [p2, p3], (error, stdout, stderr) => {
        let result = {stdout, error, stderr}
        console.log('upload.sh =====', command, result)
        if (isTypeString(stdout) || isTypeString(stderr)) resolve(result)
        if (error) reject(error)
      })
    } else {
      try {
        let commandOptions = process.platform === 'win32' ? {} : {sudo: true, admin: true, shell: '/bin/zsh'}
        exec(command, commandOptions, (error, stdout, stderr) => {
          let result = {stdout, error, stderr}
          console.log('execCommand=====', command, result)
          if (isTypeString(stdout) || isTypeString(stderr)) resolve(result)
          if (error) reject(error)
        })
      } catch (e) {
        console.log('execCommand=====', command, e)
        reject(e)
      }
    }
  })
}

//获取执行命令后的多条结果
export const readResultLines = (result) => {
  if (result) return result.split('\n').filter((item) => item.trim())
  else return []
}

//获取对象类型
const getValType = (val) => {
  return Object.prototype.toString.call(val).replace('[object ', '').replace(']', '')
}

//当前对象属性是否为字符串
const isTypeString = (val) => {
  return getValType(val) === 'String'
}

//判断是否为文件类型
const isFileType = (fileName) => {
  return fileName.lastIndexOf('.') > 0 && fileName.lastIndexOf('.') < fileName.length - 1
}

//获取文件类型
const getFileType = (fileName) => {
  return isFileType(fileName) && fileName.substring(fileName.lastIndexOf('.'), fileName.length)
}
